package com.minigame.rpc.connection;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ConnectionHolder {

    private Map<String,Connection> connectionMap = new ConcurrentHashMap<>();


    public void addConnection(String key,Connection connection){
        connectionMap.put(key, connection);
    }

    public Connection getConnection(String key){
        return connectionMap.get(key);
    }

    public void removeConnection(String key){
        Connection connection = connectionMap.remove(key);
        if(connection != null){
            connection.close();
        }
    }

    public void closeAllConnection(){
        Iterator<Map.Entry<String,Connection>> iterator = connectionMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String,Connection> entry = iterator.next();
            Connection connection = entry.getValue();
            connection.close();
            iterator.remove();
        }
    }


}
